package com.wolfsea.launcherdemo
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.core.view.get

/**
 *@desc  TopContentLayout
 *@author liuliheng
 *@time 2023/1/10  22:53
 **/
class TopContentLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : ViewGroup(context,attributeSet) {

    init {
        inflate(context, R.layout.top_content_layout, this)
        findViewById<TopContentLayoutBottom>(R.id.top_content_layout_bottom).attachContentViewGroup(
            findViewById(R.id.top_content_view_group)
        )
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        for (i in 0.until(childCount)) {
            val child = get(i)
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
        }
        setMeasuredDimension(
            MeasureSpec.getSize(widthMeasureSpec) - paddingStart - paddingEnd,
            MeasureSpec.getSize(heightMeasureSpec) - paddingTop - paddingBottom
        )
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        for (i in 0.until(childCount)) {
            val child = get(i)
            val childMeasuredWith = child.measuredWidth
            val childMeasuredHeight = child.measuredHeight
            val layoutParams = child.layoutParams as MarginLayoutParams
            child.layout(
                layoutParams.leftMargin,
                layoutParams.topMargin,
                layoutParams.leftMargin + childMeasuredWith,
                layoutParams.topMargin + childMeasuredHeight
            )
        }
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

}